//
//  LoginViewController.swift
//  MintBag
//
//  Created by wy on 2024/8/23.
//

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var topSpace: NSLayoutConstraint!
    @IBOutlet weak var tvView: UIView!
    @IBOutlet weak var areaBtn: UIButton!
    @IBOutlet weak var phoneView: UIView!
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var stateBtn: UIButton!
    @IBOutlet weak var loginBtn: UIButton!
     
    // 注册输入页 停留时长 ms
    var trackRegGuideTime: Int = 0
    // 注册输入页- phone-input 获焦失焦 时间差 ms
    var trackRegGuidePhoneTime: Int = 0
    // 注册输入页- phone-input 修改次数
    var trackRegGuidePhoneUpNum: Int = 0
    // 注册输入页- phone-input 输入次数
    var trackRegGuidePhoneInNum: Int = 0
    var privacypolicyUrl = ""      // protocalType=1
    var customerAgreementUrl = ""  // protocalType=6
    var code: String = "234"
    
    var startInTime = 0
    var startEditTime = 0
    var endEditTime = 0
    var isInput = false
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        startInTime = Int(Date().timeIntervalSince1970 * 1000)
        trackRegGuidePhoneUpNum = 0
        trackRegGuidePhoneInNum = 0
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setNavigationBarHidden(true, animated: false)
        topSpace.constant = Const.statusBarHeight + 40
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(actionTap))
        view.addGestureRecognizer(tap)
        
        NotificationCenter.default.addObserver(self, selector: #selector(valueChanged), name: UITextField.textDidChangeNotification, object: nil)
        
//        Async.main(after: 0.2) { [weak self] in
//            self?.phoneTF.becomeFirstResponder()
//        }

        let firstOpen = KeychainStore.shared.string(forKey: .firstOpen) ?? ""
        if firstOpen.isEmpty {
            let auth = AuthInfoViewController(nibName: "AuthInfoViewController", bundle: nil)
            auth.modalPresentationStyle = .fullScreen
            present(auth, animated: false)
            
            KeychainStore.shared.setString("1", key: .firstOpen)
        }

        requestProtocol()
    }
    
    func requestProtocol() {
        Http.shared.requestApi(.getProtocol) { [weak self] response in
            if (response["code"] as? Int) == 200, let list = response["data"] as? [[String: Any]] {
                guard let self = self else { return }
                self.privacypolicyUrl = list.filter({ $0["protocalType"] as? Int == 1 }).first?["url"] as? String ?? ""
                self.customerAgreementUrl = list.filter({ $0["protocalType"] as? Int == 6 }).first?["url"] as? String ?? ""
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewDidLayoutSubviews() {
        tvView.addTopCorners()
        phoneView.addShadow()
    }
        
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    @objc func actionTap() {
        phoneTF.endEditing(true)
    }
    
    @objc func valueChanged() {
        var text = phoneTF.text ?? ""
        text = text.replacingOccurrences(of: "-", with: "")
        if phoneTF.isEditing, text.count>3 {
            var nums = text.map { String($0) }
            if nums[3] != "-" {
                nums.insert("-", at: 3)
            }
            if nums.count>8, nums[8] != "-" {
                nums.insert("-", at: 8)
            }
            phoneTF.text = nums.joined()
            Async.main(after: 0.1) { [weak self] in
                // 光标移动到最后
                let position = self?.phoneTF.endOfDocument
                self?.phoneTF.selectedTextRange = self?.phoneTF.textRange(from: position!, to: position!)
            }
        }

        var regx = (phoneTF.text ?? "").replacingOccurrences(of: "-", with: "").count != 10
        if !regx {
            if NSString(string: phoneTF.text!).substring(to: 1) == "0" {
                regx = true
            }
        }
        loginBtn.setBackgroundImage(UIImage(named:regx ? "login_btn_n" : "login_btn_s"), for: .normal)
    }

    @IBAction func actionArea(_ sender: Any) {
    }
    
    @IBAction func actionProtocol1(_ sender: Any) {
        if privacypolicyUrl.isEmpty {
            return
        }
        let vc = InnerWebViewController()
        vc.url = URL(string: privacypolicyUrl)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func actionProtocol2(_ sender: Any) {
        if customerAgreementUrl.isEmpty {
            return
        }
        let vc = InnerWebViewController()
        vc.url = URL(string: customerAgreementUrl)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func actionStatus(_ sender: Any) {
        stateBtn.isSelected = !stateBtn.isSelected
    }
    
    @IBAction func actionLogin(_ sender: Any) {
        phoneTF.resignFirstResponder()
        if (phoneTF.text ?? "").replacingOccurrences(of: "-", with: "").count != 10 {
            showToast("Please fill in correct phone number")
            return
        }
        if !stateBtn.isSelected {
            showToast("Please agree the agreements")
            return
        }
        
        trackRegGuideTime = Int(Date().timeIntervalSince1970 * 1000) - startInTime
        trackRegGuidePhoneTime = endEditTime - startEditTime
        
        let vc = VerifyCodeViewController(nibName: "VerifyCodeViewController", bundle: nil)
        vc.phone = phoneTF.text?.replacingOccurrences(of: "-", with: "")
        vc.code = code
        vc.trackRegGuideTime = trackRegGuideTime
        vc.trackRegGuidePhoneTime = trackRegGuidePhoneTime
        vc.trackRegGuidePhoneUpNum = trackRegGuidePhoneUpNum - 1
        vc.trackRegGuidePhoneInNum = trackRegGuidePhoneInNum
        navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension LoginViewController: UITextFieldDelegate {
    func textFieldDidBeginEditing(_ textField: UITextField) {
        startEditTime = Int(Date().timeIntervalSince1970 * 1000)
        endEditTime = 0
        trackRegGuidePhoneUpNum += 1
    }
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        endEditTime = Int(Date().timeIntervalSince1970 * 1000)
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return textField.resignFirstResponder()
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if !string.isEmpty {
            trackRegGuidePhoneInNum += 1
        }
        if (textField.text ?? "").replacingOccurrences(of: "-", with: "").count + string.count > 10 {
            return false
        }
        return true
    }
}

extension UIView {
    
    class ECCAGradientLayer: CAGradientLayer {
        convenience init(frame: CGRect,cornerRadius: CGFloat = 12, corners: UIRectCorner = .allCorners) {
            self.init()
            self.frame = frame
            self.backgroundColor = UIColor.white.cgColor
            let maskLayer = CAShapeLayer()
            maskLayer.frame = frame
            maskLayer.path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: cornerRadius, height: cornerRadius)).cgPath
            self.mask = maskLayer
        }
    }

    /// 给view同时添加阴影和圆角
    /// - Parameter cornerRadius: 圆角半径
    /// - Parameter corners: 指定位置设为圆角
    func addShadow(_ cornerRadius: CGFloat = 10, corners: UIRectCorner = .allCorners, color: UIColor? = nil) {
        layoutIfNeeded()
        
        self.layer.sublayers?.forEach({ e in
            if e.isKind(of: ECCAGradientLayer.self) {
                e.removeFromSuperlayer()
            }
        })
       
        // 添加圆角图层
        let radiusLayer = ECCAGradientLayer(frame: bounds, cornerRadius: cornerRadius, corners: corners)
        layer.insertSublayer(radiusLayer, at: 0)
        // 设置阴影
        layer.shadowColor = (color ?? UIColor.gray.withAlphaComponent(0.1)).cgColor
        layer.shadowOffset = CGSize(width: 0, height: 4)
        layer.shadowRadius = cornerRadius
        layer.shadowOpacity = 1
        layer.shadowPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: 20, height: 20)).cgPath
    }

    func addBottomCorners(_ radius: CGFloat = 30) {
        self.roundCorner(corners: [.bottomLeft,.bottomRight], radius: radius)
    }
    
    func addTopCorners(_ radius: CGFloat = 30) {
        self.roundCorner(corners: [.topRight,.topLeft], radius: radius)
    }
    
    func roundCorner(corners: UIRectCorner, radius: CGFloat) {
        self.layoutIfNeeded()
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        layer.mask = mask
    }
    func noCornerMasks() {
        layer.mask = nil
    }
    
    func snapshotImage() -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0)
        guard let current = UIGraphicsGetCurrentContext() else {
            return nil
        }
        self.layer.render(in: current)
        let snap = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext();
        return snap;
    }
    
    /// 部分圆角 @available(iOS 11.0, *)
    /// - Parameters:
    ///   - cornerMask:需要实现为圆角的角，可传入多个
    ///   - radius: 圆角半径
    func cornerRadius(corners: CACornerMask, radius: CGFloat) {
        self.layer.cornerRadius = radius
        self.layer.maskedCorners = corners
    }
}
